/**
 * 路由安全守卫
 */
import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Loading } from 'element-ui'
import { getToken, setToken } from '@/utils/auth'
import allPermission from '@/utils/allPermission'
const defaultSettings = require('@/settings.js')

NProgress.configure({ easing: 'linear', speed: 500, showSpinner: true })

let loadingInstance = null
router.beforeEach(async(to, from, next) => {
  var meta = to.meta
  if (meta) {
    if (meta.auth === false) {
      defaultSettings.whiteList.add(to.name)
    }
  }
  NProgress.start()
  loadingInstance = Loading.service({
    fullscreen: true,
    text: '页面渲染中...',
    customClass: 'common-loading'
  })
  if (!getToken()) {
    if (to.query.accessToken) {
      store.commit('SET_TOKEN', to.query.accessToken)
      setToken(to.query.accessToken)
    }
  }
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
      if (loadingInstance) {
        loadingInstance.close()
      }
    } else {
      try {
        const userInfo = await store.dispatch('getInfo')
        const roles = userInfo.roles
        if (defaultSettings.openPagePer) {
          if (to.name !== 'noPermission' && !allPermission.hasMenu(to.name, to.meta.valid)) {
            next(`/noPermission?permission=${to.name}&menuName=${to.meta.title}`)
            return
          }
        }
        await store.dispatch('GenerateRoutes', { roles })
        next()
      } catch (error) {
        console.log(error)
        await store.dispatch('logout')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
        if (loadingInstance) {
          loadingInstance.close()
        }
      }
    }
  } else {
    if (defaultSettings.whiteList.has(to.name)) {
      /**
       * 白名单
       */
      next()
    } else {
      /**
       * 跳转至登录
       */
      next(`/login?redirect=${to.path}`)
      NProgress.done()
      if (loadingInstance) {
        loadingInstance.close()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
  if (loadingInstance) {
    loadingInstance.close()
  }
})
